package com.carlos.company.security.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.carlos.company.config.JwtConfig;
import com.carlos.company.security.JsonAuthentication;
import com.carlos.company.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author 李健成
 * @date 2021/10/15
 */

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private JwtConfig jwtConfig;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException {

        String jwt = JWT.create()
                .setExpiresAt(DateUtil.tomorrow())
                .setPayload("username", authentication.getName())
                .setSigner(JWTSignerUtil.none())
                .sign();
        httpServletResponse.setHeader(jwtConfig.getHeader(), jwt);

        ResultVO<Object> result = new ResultVO<>().success();
        JsonAuthentication.writeJson(httpServletRequest, httpServletResponse, result);

    }

}
